<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Core\Controller;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    public function showLoginForm(Request $request)
    {
        Session::forget('member');
        if ($request->method() == "POST") {
            $username = $request->get('username');
            $password = $request->get('password');
            $params = ['username' => $username, 'password' => md5($password)];
            $member = Member::where($params)->get();
            if (!$member = $member->first()) {
                return json_encode(['data' => ['url' => ''], 'msg' => '账号或密码错误！', 'status' => 0]);
            }
            Session::put('member', $member);
            $member->last_login_time = time();
            $member->last_login_ip = $request->getClientIp();
            $member->save();
            if ($member->type == 1) {
                $url = url('/company');
            } else {
                $url = url('/member');
            }
            return json_encode(['data' => ['url' => $url], 'msg' => '成功', 'status' => 1]);
        }
        return view('auth.login');
    }

    public function logout()
    {
        Session::forget('member');
    }
}
